import React, {Component} from 'react';
import { Form, Input, Button, Icon, Modal, message } from 'antd';
import { Link, history } from 'react-router-dom';
import './index.less';
import axios from 'axios';
import {connect} from 'react-redux';
import Bread from '../common/Bread/index';
const FormItem = Form.Item;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8'

class changepassword extends Component {
    constructor(props) {
      super(props);
      this.state = {
        confirmDirty: false,
        visible: false,
        autoCompleteResult: [],
        getCode: '',
        oldMobile: '',
      }
    }
    showModal = () => {
        this.setState({
            visible: true,
        });
    }
    handleOk = () => {
        this.setState({visible: false });
    }
    handleCancel = () => {
        this.setState({ visible: false });
    }
    handleSubmit = (e) => {
      e.preventDefault();
      const _this = this;
      const Token = localStorage.getItem("token");
      const phone = this.state.oldMobile;
      // const regExp = /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/;
      this.props.form.validateFieldsAndScroll((err, values) => {
        // console.log(values);
        if (!err) {
              var data = {
                attr1: values.oldpassword,
                telPhone: phone,
                attr2: values.code,
                password: values.confirmpassword
              }
              // console.log(values.password)
              
                axios({
                  method: 'post',
                  url: '/api/customer/user/resetPass',
                  data: data,
                  headers: {
                    'Content-Type': 'application/json',
                    Authorization:Token,
                  },
                })
                .then(function(response){
                    if(response.data.status == 'false'){
                        message.warning(response.data.message);
                        return false
                    }else if(response.data.message == '恭喜您已经成功修改密码！') {
                      _this.props.form.resetFields();
                      _this.setState({
                        visible: true
                      })
                    }
                })
            }
            else {
                console.log('Received values of form: ', values);
            }
          // this.SubmitPost(values)
      });
    }
    handleConfirmBlur = (e) => {
      const value = e.target.value;
      this.setState({ confirmDirty: this.state.confirmDirty || !!value });
    }
    compareToFirstPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && value !== form.getFieldValue('password')) {
        callback('您输入的两个密码不一致');
      } else {
        callback();
      }
    }
    validateToNextPassword = (rule, value, callback) => {
      const form = this.props.form;
      if (value && this.state.confirmDirty) {
        form.validateFields(['confirm'], { force: true });
      }
      callback();
    }

    getMobile=(e)=>{
      this.setState({
        mobile: e.target.value
      })
    }

    handleCode =()=>{
      const _this = this;
      let sec = 60;
      const clickTime = new Date().getTime();
      console.log(clickTime)
      localStorage.setItem("changePwdclickTime",clickTime);
      const mobile = this.state.oldMobile;
      const Token = localStorage.getItem("token");
      if(this.state.getCode !== '获取验证码'){
        return false;
      }
      axios({
        method: 'get',
        url: '/api/customer/rest/sendPassMsg?mobile='+ mobile,
        headers: {
          'Content-Type': 'application/json',
          Authorization:Token,
        }
      })
      .then(function(response){
        if(response.data.code == '201'){
          message.warning('请输入正确的手机号');
        }else if(response.data.code == '202'){
          message.warning('获取手机验证码失败');
        }else if(response.data.code == '200') {
          const timer = setInterval(function(){
            sec--;
            if(sec < 0){
              clearInterval(timer);
              _this.setState({
                getCode:  '获取验证码',
              })
              localStorage.setItem("changePwdclickTime","");
            }else {
              _this.setState({
                getCode:  sec + 's 后重新获取',
              })
            }
          },1000)
        }
      })
    }
    



  componentWillMount(){
    const _this = this;
    const nowDate = new Date().getTime();
    let sec = localStorage.getItem("changePwdclickTime");
    const currentTime = (nowDate - sec)/1000;
    let delta = Math.round(60 - currentTime);
    const timer = setInterval(function(){
      delta--;
      if(delta < 0){
        clearInterval(timer);
        _this.setState({
          getCode:  '获取验证码',
        })
      }else {
        _this.setState({
          getCode:  delta + 's 后重新获取',
        })
      }
    },1000)
    

    const Token = localStorage.getItem("token");
    axios({
      method: 'get',
      url: '/api/customer/user/getTel',
      headers: {
        'Content-Type': 'application/json',
        Authorization:Token,
      }
    })
    .then(function(response){
      // console.log(response)
      if(response.data.code == '200'){
        _this.setState({
            oldMobile: response.data.data,
        })
      }
    })
    .catch(function(error){
      message.error('获取手机号失败')
    })
  }

  onFocusFn=(e)=>{
    if(e.target.value == ''){
      e.target.type = 'text';
    }else{
       // console.log(e.target.value)
      e.target.type='password'
    }
  }


    render() {
      const { getFieldDecorator } = this.props.form;
      const { autoCompleteResult, visible } = this.state;
      const disabled = this.state.getCode !== '获取验证码' ? "disabled" : "";

      return (
        <div>
          <Bread bread={['账户服务',['密码修改','changePassword']]}/>
          <div className="changeBox">           
          <Form onSubmit={this.handleSubmit}> 
              <div className="changePassBox">
                  <h3 className="changeTitle">密码修改</h3>                  
                    <FormItem
                        label="原密码"
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 11 }}
                    >
                      {getFieldDecorator('oldpassword', { 
                        rules: [{ required: true, message: '请输入原密码'  }],
                      })(
                        <Input type="text" placeholder="请输入原密码" onChange = {this.onFocusFn} />
                      )}
                  </FormItem>
                  <FormItem className="namePhone"
                      label="预留手机号"
                      labelCol={{ span: 5 }}
                      wrapperCol={{ span: 11 }}
                  >
                      {getFieldDecorator('phone', {
                          rules: [{required: false, message: '请输入预留手机号'}],
                      })(
                        <div>
                            <Input className="phoneText" disabled value={this.state.oldMobile} />
                            <Button
                              className="yzmBtn"
                              type= "primary"
                              size="small"
                              disabled={disabled}
                              onClick = {this.handleCode}
                            >
                            {this.state.getCode}
                          </Button>
                        </div>    
                      )}
                  </FormItem>
                  <FormItem
                      label="短信验证码"
                      labelCol={{ span: 5 }}
                      wrapperCol={{ span: 11 }}
                  > 
                    {getFieldDecorator('code',{
                      rules: [{required: true, message: '请输入短信验证码，仅限数字', pattern: /^[0-9]+$/}]
                    })(
                      <Input type="text" placeholder="请输入短信验证码，仅限数字" maxLength={8} />
                    )}
                  </FormItem>
                  <FormItem
                    label="输入新密码"
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 11 }}
                  >
                    {getFieldDecorator('password', {
                      rules: [{
                        required: true, message: '请输入8到20个字符之间的字母、数字和符号组合密码', pattern: /^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_]+$)(?![a-z0-9]+$)(?![a-z\W_]+$)(?![0-9\W_]+$)[a-zA-Z0-9\W_]{8,20}$/
                      }, {
                        validator: this.validateToNextPassword,
                      }],
                    })(
                      <Input type="text" placeholder="请输入新的密码" maxLength={20} onChange = {this.onFocusFn} />
                    )}
                  </FormItem>
                  <FormItem
                    label="确认新密码"
                    labelCol={{ span: 5 }}
                    wrapperCol={{ span: 11 }}
                  >
                    {getFieldDecorator('confirmpassword', {
                      rules: [{
                        required: true, message: '请确认新的密码',
                      }, {
                        validator: this.compareToFirstPassword,
                      }],
                    })(
                      <Input type="text" placeholder="请确认新的密码" onChange = {this.onFocusFn} />
                    )}
                  </FormItem>
                  <div className="confirmChange">
                    <Button type="primary" htmlType="submit">确认修改</Button>
                  </div>
                </div>
            </Form>
            <Modal
              visible={visible}
              title="提示"
              onOk={this.handleOk}
              onCancel={this.handleCancel}
              footer={[
                <Button key="submit" type="primary" onClick={this.handleOk}>
                  确认
                </Button>,
              ]}
            >
              <p className="title">恭喜您已经成功修改密码！</p>
            </Modal>
          </div>
        </div>
      )
    }
  }
  
  const changePassword = Form.create()(changepassword);
export default connect((state) => {
  return { ...state };
})(changePassword);
